package com.my.lucky.service;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

public class StockRealtimeCache {
    private static final Logger LOGGER = Logger.getLogger(StockRealtimeCache.class.getName());
    private static final int THREAD_POOL_SIZE = 5;
    private static final int UPDATE_INTERVAL_MS = 1000; // 1秒更新一次
    private final ConcurrentHashMap<String, Map<String, String>> stockCache;
    private final ScheduledExecutorService scheduler;
    private final Set<String> stockCodes;
    private final AtomicBoolean isRunning;

    public StockRealtimeCache() {
        this.stockCache = new ConcurrentHashMap<>();
        this.stockCodes = ConcurrentHashMap.newKeySet();
        this.scheduler = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);
        this.isRunning = new AtomicBoolean(false);
    }

    public void addStock(String stockCode) {
        stockCodes.add(stockCode);
        if (isRunning.get()) {
            updateStockData(stockCode);
        }
    }

    public void removeStock(String stockCode) {
        stockCodes.remove(stockCode);
        stockCache.remove(stockCode);
    }

    public Map<String, String> getStockData(String stockCode) {
        return stockCache.get(stockCode);
    }

    public void start() {
        if (isRunning.compareAndSet(false, true)) {
            scheduler.scheduleAtFixedRate(this::updateAllStocks, 0, UPDATE_INTERVAL_MS, TimeUnit.MILLISECONDS);
        }
    }

    public void stop() {
        if (isRunning.compareAndSet(true, false)) {
            scheduler.shutdown();
            try {
                if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {
                    scheduler.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduler.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

    private void updateAllStocks() {
        CompletableFuture<?>[] futures = stockCodes.stream()
                .map(code -> CompletableFuture.runAsync(() -> updateStockData(code), scheduler))
                .toArray(CompletableFuture[]::new);

        CompletableFuture.allOf(futures).join();
    }

    private void updateStockData(String stockCode) {
        try {
            Map<String, String> realtimeData = SohuStockAPI.getRealtimeQuote(stockCode);
            if (!realtimeData.isEmpty()) {
                stockCache.put(stockCode, realtimeData);
                LOGGER.fine("Updated stock data for: " + stockCode);
            }
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to update stock data for: " + stockCode, e);
        }
    }

    // 获取所有缓存的股票代码
    public Set<String> getAllStockCodes() {
        return new HashSet<>(stockCodes);
    }

    // 获取所有缓存的股票数据
    public Map<String, Map<String, String>> getAllStockData() {
        return new ConcurrentHashMap<>(stockCache);
    }


} 